package com.sina.shop.manage.controller.storage.goods;

import com.sina.shop.core.exception.server.UpdateException;
import com.sina.shop.domain.carousel.Carousel;
import com.sina.shop.domain.goods.Goods;
import com.sina.shop.domain.goods.GoodsPhoto;
import com.sina.shop.manage.form.StorageForm;
import com.sina.shop.manage.service.carousel.CarouselManageService;
import com.sina.shop.manage.service.goods.GoodsManageService;
import com.sina.shop.manage.service.goods.GoodsPhotoManageService;
import com.sina.shop.manage.storage.CloudStorageException;
import com.sina.shop.util.DateUtils;
import com.sina.shop.web.BaseController;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sina.shop.util.FileUploadUtils.uploadToTemp;
import static com.sina.shop.util.FileUtils.deleteFile;

/**
 * 云存储
 */
@Controller("storageGoodsPhotoController")
@RequestMapping("storageGoodsPhoto")
public class StorageGoodsPhotoController extends BaseController implements ServletContextAware {


    private ServletContext servletContext;

    @Autowired
    @Qualifier("goodsPhotoManageService")
    private GoodsPhotoManageService goodsPhotoManageService;

    @Autowired
    @Qualifier("goodsManageService")
    private GoodsManageService goodsManageService;

    @Autowired
    @Qualifier("sinaStorageGoodsPhotoManager")
    private SinaStorageGoodsPhotoManager sinaStorageGoodsPhotoManager;

    @Override
    public void setServletContext(ServletContext servletContext) {
        this.servletContext = servletContext;
    }


    @RequestMapping(value = "goodsPhoto/upload", method = RequestMethod.GET)
    public ModelAndView uploadView() {
        ModelAndView mv = new ModelAndView("storage/uploadGoodsPhoto");

        List<Goods> list = goodsManageService.getGoodsList();
        String pertten = DateUtils.LocalDateFormatter("yyyyMMdd");
        mv.addObject("pertten", "http://sinacloud.net/finance-documents/" + pertten);
        mv.addObject("list", list);

        return mv;
    }

    @RequestMapping(value = "goodsPhoto/upload", headers = {"Content-Type=multipart/form-data"}
            , method = RequestMethod.POST)
    public ModelAndView documentUpload(@Valid StorageForm form) {

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(5);
        File destFile = null;
        GoodsPhoto goodsPhoto = null;
        try {
            destFile = uploadToTemp(servletContext, form.getFile());

            LOG.debug("file[{}] temp to file path : {}", form.getFile().getOriginalFilename(), destFile);

            // 上传到 新浪云
            goodsPhoto = sinaStorageGoodsPhotoManager.uploadGoodsPhoto(form, destFile);

            //添加上传者
            //String name = (String) SecurityUtils.getSubject().getSession().getAttribute("username");
            //carousel.setName(name);
            goodsPhoto.setName(form.getName());
            goodsPhoto.setSort(form.getSort());
            Goods goods = new Goods();
            goods.setId(form.getId());
            goodsPhoto.setGoods(goods);
            //数据库添加  出现异常则添加失败。
            try {
                goodsPhotoManageService.saveGoodsPhoto(goodsPhoto);
                result.put(STATUS, Boolean.TRUE);
                result.put(MSG, "上传成功");
            } catch (UpdateException e) {
                try {
                    sinaStorageGoodsPhotoManager.deleteGoodsPhoto(goodsPhoto);
                } catch (CloudStorageException c) {

                }
                result.put(STATUS, Boolean.FALSE);
                result.put(MSG, e.getMessage());
            }
        } catch (Exception e) {
            result.put(STATUS, Boolean.FALSE);
            result.put(MSG, e.getMessage());
        } finally {
            deleteFile(destFile);
        }
        mv.addObject(RESULT, result);
        return mv;
    }

    @RequestMapping(value = "goodsPhoto/download", method = RequestMethod.GET)
    public ModelAndView goodsPhotoDownload(@Valid GoodsPhoto goodsPhoto, HttpServletResponse response) {

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);

        goodsPhoto = goodsPhotoManageService.get(GoodsPhoto.class, goodsPhoto.getId());

        if (goodsPhoto == null) {
            result.put(STATUS, Boolean.FALSE);
            result.put(MSG, "下载失败，文件不存在");
            mv.addObject(RESULT, result);
            return mv;
        }

        try {
            response.setHeader("Content-Disposition",
                    "attachment;Filename=" + URLEncoder.encode(goodsPhoto.getUrl().substring(8, goodsPhoto.getUrl().length()), "UTF-8")
            );
            // 从新浪云下载
            sinaStorageGoodsPhotoManager.download(goodsPhoto, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response.getOutputStream() != null) {
                    response.getOutputStream().close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return mv;
    }

    @RequestMapping(value = "goodsPhoto/delete", method = RequestMethod.GET)
    public ModelAndView goodsPhotoDelete() {

        ModelAndView mv = new ModelAndView("resultView");
        Map<String, Object> result = new HashMap<>(4);
        GoodsPhoto goodsPhoto = new GoodsPhoto();
        goodsPhoto.setUrl("20171128/29ab9911-b741-47e2-bebf-88eb9a4abc93.txt");

        try {
            sinaStorageGoodsPhotoManager.deleteGoodsPhoto(goodsPhoto);
            result.put(STATUS, Boolean.TRUE);
            result.put(MSG, "删除成功");
        } catch (CloudStorageException e) {
            result.put(STATUS, Boolean.FALSE);
            result.put(MSG, "删除失败");
        }
        mv.addObject(RESULT, result);

        return mv;
    }

}
